# app.py文件实现了UI功能下点击按钮爬取数据
# 为了延申功能，将app中爬取的功能抽象成一个新类，通过调取类实现
# 新类的名字叫 DataFetcher
# UI下获取数据
import time
import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv
from datetime import datetime

class DataFetcher:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.driver = None

    def fetch_data(self):
        try:
            game_login_url = "https://ts1.x1.asia.travian.com/"
            base_count_list_url = "https://ts1.x1.asia.travian.com/statistics/player/overview?page="

            options = Options()
            options.add_argument("--disable-gpu")
            self.driver = webdriver.Chrome(options=options)
            self.driver.set_window_size(1200, 900)

            self.driver.get(game_login_url)
            time.sleep(3)  # 等待页面加载

            username_field = self.driver.find_element(By.NAME, "name")
            username_field.send_keys(self.username)  # 替换为你的用户名
            time.sleep(1)

            password_field = self.driver.find_element(By.NAME, "password")
            password_field.send_keys(self.password)  # 替换为你的密码
            time.sleep(1)

            login_button = self.driver.find_element(By.CSS_SELECTOR, "button[type='submit']")
            login_button.click()
            time.sleep(3)  # 等待登录完成

            current_date = datetime.now().strftime("%Y%m%d")
            csv_filename = f"{current_date}.csv"

            with open(csv_filename, mode="w", newline="", encoding="utf-8") as file:
                writer = csv.writer(file)
                writer.writerow(["玩家", "统计时间", "玩家排名", "人口", "村莊"])

                page = 1
                while True:
                    count_list_url = f"{base_count_list_url}{page}"
                    self.driver.get(count_list_url)
                    time.sleep(2)  # 等待页面加载

                    # 爬取当前页的数据
                    try:
                        WebDriverWait(self.driver, 3).until(
                            EC.presence_of_element_located((By.XPATH, "//tbody[@class='hoverable']"))
                        )
                        rows = self.driver.find_elements(By.XPATH, "//tbody[@class='hoverable']/tr[@class='hover']")
                        for row in rows:
                            try:
                                rank = re.sub(r'\u202e|\u202c|\u202d', '',
                                              row.find_element(By.XPATH, ".//td[1]").text.strip())
                                player_name = re.sub(r'\u202e|\u202c|\u202d', '',
                                                     row.find_element(By.XPATH, ".//td[3]/a").text.strip())
                                population = re.sub(r'\u202e|\u202c|\u202d', '',
                                                    row.find_element(By.XPATH, ".//td[6]").text.strip().replace(",", ""))
                                villages = re.sub(r'\u202e|\u202c|\u202d', '',
                                                  row.find_element(By.XPATH, ".//td[7]").text.strip())

                                writer.writerow([player_name, current_date, rank, population, villages])
                            except Exception as e:
                                print(f"某些元素未找到：{e}")
                    except Exception as e:
                        print(f"页面加载超时或元素未找到：{e}")
                        break

                    # 判断是否到达最后一页
                    try:
                        next_button = WebDriverWait(self.driver, 3).until(
                            EC.presence_of_element_located((By.XPATH, "//img[@class='next disabled']"))
                        )
                        if next_button:
                            print(f"到达最后一页：第 {page} 页")
                            break
                    except:
                        pass

                    page += 1

        except Exception as e:
            print(f"发生错误：{e}")
            return False
        finally:
            if self.driver:
                self.driver.quit()
            return True

